/**
 * header数据列表的分页组件
 */
let headerPageComponent;

/**
 * 为添加config的panel增加校验逻辑
 *
 * @param addConfigPanel 添加config panel
 */
function addValidatorForEditConfigPanel(addConfigPanel) {
    addConfigPanel.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            code: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The code is required'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9\-\\.]+$/,
                        message: "Only characters, numbers, \"-\" or \".\" are allowed"
                    },
                    remote: {
                        type: 'GET',
                        headers: {
                            Authorization: JwtTokenUtils.getBearerHeader()
                        },
                        message: "No. already exists, please replace with a new one",
                        url: "/service/datacenter/config/checkConfigCodeExists",
                        delay: 1000
                    }
                }
            },
            name: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            }
        }
    });
}

/**
 * 为修改config item的panel增加校验
 *
 * @param modifyItemDiv 修改 config item的panel
 */
function addValidatorForEditConfigItemPanel(modifyItemDiv) {
    modifyItemDiv.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            environment: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The environment is required'
                    }
                }
            }
        }
    });
}

/**
 * 添加Config
 * @param addConfigPanel config添加面板
 */
function addConfig(addConfigPanel) {
    let requestData = {};
    requestData.code = addConfigPanel.find(".code-value").val();
    requestData.name = addConfigPanel.find(".name-value").val();
    requestData.defaultValue = addConfigPanel.find(".default-value").val();
    requestData.description = addConfigPanel.find(".description-value").val();

    $.ajax({
        type: 'POST',
        url: "/service/datacenter/config/addConfig",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            addConfigPanel.remove();
            $(".component .add-new-panel").removeClass("disable");
            $(".component .app-list").empty();
            headerPageComponent.query();
        }
    });
}

/**
 * 修改config
 *
 * @param updateConfigPanel config修改面板
 */
function updateConfig(updateConfigPanel) {
    let requestData = {};
    requestData.id = updateConfigPanel.attr("config-id");
    requestData.name = updateConfigPanel.find(".name-value").val();
    requestData.defaultValue = updateConfigPanel.find(".default-value").val();
    requestData.description = updateConfigPanel.find(".description-value").val();

    $.ajax({
        type: 'PUT',
        url: "/service/datacenter/config/updateConfig",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            headerPageComponent.refreshData();
        }
    });
}

/**
 * 查询config列表
 *
 * @param pageDiv 分页组件
 * @param query 查询条件
 * @param pageSize 每页条数
 * @param pageNumber 当前页数
 * @param callback 回调方法
 */
function queryConfigs(pageComponent) {
    let requestData = {
        pageSize: pageComponent.size,
        pageNumber: pageComponent.number,
        query: pageComponent.queryParam
    };
    $.ajax({
        type: 'POST',
        url: "/service/datacenter/config/page/queryConfigs",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function (data) {
            $(".component .data-list").empty();

            let pageParams = {};
            pageParams.totalPages = data.totalPages;
            pageParams.number = data.number;
            pageParams.size = data.size;

            pageComponent.rebuildHtmlDom(pageParams);

            let content = data.content;

            for (let i = 0; i < content.length; i++) {
                let config = content[i];
                let configPanel = $(".component .templates .config-panel").clone();
                configPanel.find(".panel-title").text(config.name);
                configPanel.attr("config-id", config.id);
                configPanel.css("display", "block");
                configPanel.find(".id-value").text(config.id);
                configPanel.find(".code-value").text(config.code);
                configPanel.find(".name-value").text(config.name);
                configPanel.find(".default-value").text(config.defaultValue);
                configPanel.find(".description-value").text(config.description);

                configPanel.find(".edit-button").click(function () {
                    let editConfigPanel = $(".component .templates .edit-data-panel").clone();
                    editConfigPanel.attr("config-id", config.id);
                    editConfigPanel.find(".panel-title").text("Modify Config");
                    editConfigPanel.find(".code-value").val(config.code);
                    editConfigPanel.find(".code-value").attr("disabled", "disabled");
                    editConfigPanel.find(".code-label").removeClass("required");
                    editConfigPanel.find(".name-value").val(config.name);
                    editConfigPanel.find(".description-value").text(config.description);
                    editConfigPanel.find(".default-value").text(config.defaultValue);

                    editConfigPanel.find(".save-button").click(function () {
                        editConfigPanel.bootstrapValidator('validate');
                        let invalidFields = editConfigPanel.data('bootstrapValidator').getInvalidFields();
                        if (invalidFields.length === 0) {
                            updateConfig(editConfigPanel);
                        }
                    });

                    editConfigPanel.find(".cancel-button").click(function () {
                        editConfigPanel.remove();
                        configPanel.css("display", "block");
                    });

                    editConfigPanel.insertBefore($(this).parents(".data-panel"));
                    addValidatorForEditConfigPanel(editConfigPanel);
                    configPanel.css("display", "none");
                });

                configPanel.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this config?", function () {
                        $.ajax({
                            type: 'DELETE',
                            url: "/service/datacenter/config/deleteConfig/" + config.id,
                            contentType: "application/json;charset=UTF-8",
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                pageComponent.refreshData();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                configPanel.find(".config-item-list-show-button").click(function () {
                    if ($(this).hasClass("open")) {
                        $(this).removeClass("open");
                        configPanel.find(".item-table").removeClass("expansion");
                    } else if (configPanel.find(".item-table").hasClass("queried")) {
                        $(this).addClass("open");
                        configPanel.find(".item-table").addClass("expansion");
                    } else {
                        queryConfigItems(configPanel);
                    }
                });

                let addConfigItemPanel = configPanel.find(".add-config-item-panel");
                configPanel.find(".add-config-item-button").click(function () {
                    addConfigItemPanel.addClass("show");
                });

                addConfigItemPanel.find(".show-other-attribute-button").click(function () {
                    let otherAttribute = addConfigItemPanel.find(".other-attribute");
                    if (otherAttribute.hasClass("show")) {
                        otherAttribute.removeClass("show");
                    } else {
                        otherAttribute.addClass("show");
                    }
                });

                addConfigItemPanel.find(".environment-element ul li").click(function () {
                    addConfigItemPanel.find(".environment-element .selected-item").attr("value", $(this).attr("value"));
                    addConfigItemPanel.find(".environment-element .selected-item").text($(this).text());
                });

                addConfigItemPanel.find(".close-button").click(function () {
                    addConfigItemPanel.removeClass("show");
                });

                addConfigItemPanel.find(".reset-button").click(function () {
                    addConfigItemPanel.find("input").val("");
                    addConfigItemPanel.find("textarea").val("");
                    addConfigItemPanel.data('bootstrapValidator').resetForm(false);
                });

                addConfigItemPanel.find(".ok-button").click(function () {
                    addConfigItem(configPanel);
                });

                $(".component .data-list").append(configPanel);
            }
        }
    });
}

/**
 * 添加configItem
 *
 * @param configPanel configPanel
 */
function addConfigItem(configPanel) {
    let configId = configPanel.attr("config-id");
    let addConfigItemPanel = configPanel.find(".add-config-item-panel");

    let requestData = {};
    requestData.environment = addConfigItemPanel.find(".environment-element .selected-item").attr("value");
    requestData.value = addConfigItemPanel.find(".value-value").val();
    requestData.description = addConfigItemPanel.find(".description-value-textarea").val();
    requestData.configId = configId;

    $.ajax({
        type: 'POST',
        url: "/service/datacenter/config/addConfigItem",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            console.log("Add config item success ...");
            queryConfigItems(configPanel);
        }
    });
}

/**
 * config item的修改按钮点击事件
 *
 * @param configItemPanel config item panel
 * @param configItem config item
 */
function handleModifyLookItemButtonClick(configItemPanel, configItem) {
    if (configItemPanel.children(".edit-item-panel").length !== 0) {
        return;
    }
    let modifyItemDiv = $(".component .templates .edit-item-panel").clone();
    modifyItemDiv.find(".environment-value").attr("disabled", "disabled");
    modifyItemDiv.find(".environment-value").val(configItem.environment);
    modifyItemDiv.find(".value-value").val(configItem.value);
    addValidatorForEditConfigItemPanel(modifyItemDiv);

    modifyItemDiv.find(".show-other-attribute-button").click(function () {
        let otherAttribute = modifyItemDiv.find(".other-attribute");
        if (otherAttribute.hasClass("show")) {
            otherAttribute.removeClass("show");
        } else {
            otherAttribute.addClass("show");
        }
    });

    modifyItemDiv.find(".cancel-button").click(function () {
        modifyItemDiv.remove();
    });
    modifyItemDiv.find(".save-button").click(function () {
        let invalidFields = modifyItemDiv.data('bootstrapValidator').getInvalidFields();
        if (invalidFields.length > 0) {
            return;
        }
        let requestData = {
            id: configItem.id,
            name: modifyItemDiv.find(".name-value").val(),
            value: modifyItemDiv.find(".value-value").val(),
            order: modifyItemDiv.find(".order-value").val(),
            lang: modifyItemDiv.find(".lang-value").val(),
            description: modifyItemDiv.find(".description-value").val()
        };
        $.ajax({
            type: "PUT",
            contentType: "application/json;charset=utf-8",
            url: "/service/datacenter/config/updateConfigItem",
            dataType: "json",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function () {
                let dataPanel = $(configItemPanel.parents(".data-panel")[0]);
                queryConfigItems(dataPanel);
            }
        });
    });
    modifyItemDiv.insertAfter(configItemPanel.children(".self"));
}

/**
 * 查询config项
 *
 * @param dataPanel dataPanel
 */
function queryConfigItems(dataPanel) {
    $.ajax({
        type: 'GET',
        contentType: "application/json;charset=UTF-8",
        url: "/service/datacenter/config/queryConfigItems/" + dataPanel.attr("config-id"),
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            let itemTable = dataPanel.find(".config-item-list-wrap .item-table");
            let itemList = itemTable.find(".item-list");
            itemList.empty();

            itemTable.addClass("expansion");
            if (!itemTable.hasClass("queried")) {
                itemTable.addClass("queried");
            }
            dataPanel.find(".item-list-show-button").addClass("open");
            for (let i = 0; i < data.length; i++) {
                let configItem = data[i];
                let configItemPanel = $(".component .templates .item-panel").clone();
                configItemPanel.attr("id", configItem.id);
                configItemPanel.find(".id-div").text(configItem.id);
                configItemPanel.find(".environment-div").text(configItem.environment);
                configItemPanel.find(".value-div").text(configItem.value);

                configItemPanel.find(".modify-button").click(function () {
                    handleModifyLookItemButtonClick(configItemPanel, configItem);
                });

                configItemPanel.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this config item?", function () {
                        $.ajax({
                            type: 'DELETE',
                            url: "/service/datacenter/config/deleteConfigItem/" + configItem.id,
                            contentType: "application/json;charset=UTF-8",
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                queryConfigItems(dataPanel);
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                itemList.append(configItemPanel);
            }
        }
    });
}

/**
 * 添加按钮点击事件处理
 * 添加新微服务div显示
 */
function addNewHandle() {
    if ($(".component .add-new-panel").hasClass("disable")) {
        return;
    }

    let addPanel = $(".component .templates .edit-data-panel").clone();
    addPanel.css("margin-bottom", "0");
    addPanel.find(".panel-title").text("Add Config");
    addPanel.find(".save-button").click(function () {
        addPanel.bootstrapValidator('validate');
        let invalidFields = addPanel.data('bootstrapValidator').getInvalidFields();
        if (invalidFields.length == 0) {
            addConfig(addPanel);
        }
    });

    addPanel.find(".cancel-button").click(function () {
        addPanel.remove();
        $(".component .add-new-panel").removeClass("disable");
    });

    addValidatorForEditConfigPanel(addPanel);

    $(".component .add-div").append(addPanel);
    $(".component .add-new-panel").addClass("disable");
}

/**
 * 页面启动完成事件
 *
 */
$(document).ready(function () {
    headerPageComponent = PageComponentUtils.createPageComponent({
        size: 10,
        number: 0,
        container: $(".component .data-div"),
        queryParam: "",
        doQuery: (pageComponent) => {
            queryConfigs(pageComponent);
        }
    });

    headerPageComponent.query();

    $(".component .query-div .operation-div .query-button").click(function () {
        let queryParam = $(".component .query-div .query-input").val();
        headerPageComponent.query(queryParam);
    });

    $(".component .query-div .query-form .query-input").keydown(function (e) {
        if (e.keyCode == 13) {
            let queryParam = $(".component .query-div .query-input").val();
            headerPageComponent.query(queryParam);
        }
    });
});
